layui.use(['jquery','element','table','form','laypage','laytpl'],function () {
    var $ = layui.$
        ,element = layui.element
        ,form = layui.form
        ,layPage = layui.laypage
        ,laytpl = layui.laytpl;

    //校验登录状态
    if(isNotLogIn()){
        return;
    }
    //默认受惠类型为农村低保,乡镇为全部,总条数为0
    var type = "1";
    var village = "";
    var count = 0;
    //信息的格式
    var beneficiaryTpl = "{{# layui.each(d.data, function(index, item){ }}<tr itemid=\"{{item.BENEFICIARY_ID}}\"><td><input type=\"checkbox\" name=\"checked\" lay-skin=\"primary\" lay-filter=\"choose\"></td><td>{{item.BENEFICIARY_NAME}}</td><td>{{item.ADDRESS}}</td><td>{{item.STANDARDS}}</td><td>{{item.BENEFICIARY_TYPE}}</td><td>{{item.VILLAGE_NAME}}</td><td><form class='layui-form' action=''><div class='layui-input-block'><input {{# if ( '1'==item.VALID_TAG){ }} checked= 'true'{{# } }} name='open' lay-skin='switch' lay-filter='isValid' lay-text='是|否' type='checkbox'></div></form></td><td>{{item.CREATE_USER_NAME}}</td><td>{{item.CREATE_TIME}}</td><td><button class='layui-btn layui-btn-normal layui-btn-sm edit-btn'><i class='layui-icon'>&#xe642;</i></button></td><td><button class='layui-btn layui-btn-sm layui-btn-danger delete-btn'><i class='layui-icon'>&#xe640;</i></button></td></tr>{{# }); }}";
    //获取乡镇信息
    getVillageInfo(village);
    //获取受惠人信息,默认查全部
    getBeneficiaryInfo(type,village);
    //tab切换时重新加载表格
    element.on('tab(beneficiary)', function(data){
        var beneficiaryType = $(this).attr("lay-id");
        if(beneficiaryType==type){
            return;
        }
        type = beneficiaryType;
        //切换类型时,将全选按钮置为未选择
        //重新加载一个表格
        getBeneficiaryInfo(beneficiaryType,village,0,10);
        removeAllSel();
    });

    /**
     * 获取乡镇信息
     * @param villageId
     */
    function getVillageInfo(villageId){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var index = layer.load(3);
        $.ajax({
            url : "/CivilAffairs/manager/getVillageInfo",
            type : "post",
            data : {"villageId":villageId,"isManager":true},
            async : false,
            dataType : "json",
            success : function(result) {
                layer.close(index);
                if(checkResult(result)){
                    $(".village-div").html(result.data);
                }
                form.render('select');
                //选择乡镇也重新加载表格
                form.on('select(village-filter)', function(data){
                    var villageCheck = data.value; //得到被选中的值
                    if(villageCheck!=village){
                        village = villageCheck;
                        //重新加载一个表格
                        getBeneficiaryInfo(type,village,0,10);
                        removeAllSel();
                    }
                });
            },
            error:function(result){
                layer.close(index);
                reqError(result,"获取乡镇信息异常");
            }
        });
    }

    //获取受惠人信息
    function getBeneficiaryInfo(beneficiaryType,villageId,page,limit){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        beneficiaryType = 0==beneficiaryType?"":beneficiaryType;
        page = isNull(page)?0:page;
        limit = isNull(limit)?10:limit;
        var index = layer.load(3);
        //清空当前数据
        $(".beneficiary_content").html("");
        $.ajax({
            url:"/CivilAffairs/manager/getBeneficiaryInfo",
            type : "post",
            data : {"beneficiaryType":beneficiaryType,"villageId":villageId,"page":page,"limit":limit},
            async : false,
            dataType : "json",
            success : function(result) {
                layer.close(index);
                if(checkResult(result)){
                    laytpl(beneficiaryTpl).render(result.data.data, function(html) {
                        $(".beneficiary_content").html(html);
                    });
                    //重新渲染
                    form.render('checkbox');
                    //需要重新加载分页
                    if(count!=result.data.count ||beneficiaryType != type||villageId != village){
                        count = result.data.count;
                        type = beneficiaryType;
                        village = villageId;
                        //分页组件
                        layPage.render({
                            elem: 'news-page'
                            ,count: result.data.count //数据总数，从服务端得到
                            ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                            ,jump: function(obj, first){
                                //首次不执行
                                if(!first){
                                    console.log("not first");
                                    getBeneficiaryInfo(beneficiaryType,villageId,obj.curr,obj.limit);
                                }
                            }
                        });
                    }
                }
            },
            error : function(result) {
                layer.close(index);
                reqError(result,"管理员获取新闻异常");
            }
        });
    }

    //全选
    form.on('checkbox(selectAll)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[name="checked"]:not([name="open"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //添加信息
    $(".beneficiaryAdd_btn").click(function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        //添加
        $(window).one("resize",function(){
            var index = layui.layer.open({
                title : "录入信息",
                type : 2,
                content : "beneficiaryAdd.html",
                success : function(layero, index){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回信息列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500)
                }
            });
            layui.layer.full(index);
        }).resize();
    });

    //编辑信息
    $("body").on("click",".edit-btn",function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var beneficiaryId = $(this).parents("tr").attr("itemid");
        $(window).one("resize",function(){
            var index = layui.layer.open({
                title : "编辑信息",
                type : 2,
                content : "beneficiaryAdd.html?beneficiaryId="+beneficiaryId,
                success : function(layero, index){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回信息列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500)
                }
            });
            layui.layer.full(index);
        }).resize();
    });


    //删除
    $("body").on("click",".delete-btn",function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var _this = $(this);
        layer.confirm('确定删除此信息？',{icon:3, title:'提示信息'},function(index){
            //_this.parents("tr").remove();
            var beneficiaryId = _this.parents("tr").attr("itemid");
            deleteBeneficiary(beneficiaryId);
            layer.close(index);
        });
    });

    //信息内容有效与否的切换
    form.on('switch(isValid)', function(data){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var isValid = this.checked ?"1":"0";
        var beneficiaryId = $(this).parents("tr").attr("itemid");
        var index = layer.load(3);
        $.ajax({
            url:"/CivilAffairs/manager/changeValidTag",
            type:"post",
            data:{"isValid":isValid,"dataId":beneficiaryId,"dataType":"beneficiary"},
            dataType:"json",
            success:function(result){
                layer.close(index);
                if(checkResult(result)){
                    layer.msg(result.detail,{icon:6});
                }
            },
            error : function(result) {
                layer.close(index);
                console.log((this.checked?"展示":"不展示")+"新闻:"+result.status+","+result.statusMessage+",newsId:"+newsId);
                layer.msg("切换信息展示标识异常,请稍后重试",{icon:2});
            }
        });

    });

    //删除信息
    function deleteBeneficiary(beneficiaryId,isAllDel){
        if(isNull(beneficiaryId)){
            return;
        }
        $.ajax({
            url : "/CivilAffairs/manager/deleteBeneficiary",
            type : "post",
            data : {"beneficiaryId":beneficiaryId},
            async : false,
            dataType : "json",
            success : function(result) {
                if(checkResult(result) && !isAllDel){
                    getBeneficiaryInfo(type,village,0,10);
                }
            },
            error:function(result){
                reqError(result,"删除信息异常");
            }
        });
    }

    //批量删除
    $(".batchDel").click(function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var $checkbox = $('.beneficiary_content tr input[name="checked"]');
        var $checked = $('.beneficiary_content tr input[name="checked"]:checked');
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                //删除数据
                $checked.each(function(){
                    var beneficiaryId = $(this).parents("tr").attr("itemid");
                    deleteBeneficiary(beneficiaryId,true);
                });
                getBeneficiaryInfo(type,village,0,10);
                layer.close(index);
                layer.msg("删除成功",{icon:6});
            })
        }else{
            layer.msg("请选择需要删除的信息");
        }
    });

    var searchCount = 0;
    var name = "";
    //搜索
    $(".search_btn").click(function () {
        var searchName = $(".search_input").val();
        if(isNull(searchName)){
            layer.msg("请输入要搜索的名字");
            return;
        }
        searchNameInfo(searchName);
    });

    //判断回车,回车点击搜索按钮
    $(document).keyup(function (e) {//捕获文档对象的按键弹起事件
        if (e.keyCode == 13) {
            $(".search_btn").click();
        }
    });

    function searchNameInfo(searchName,page,limit){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        page = isNull(page)?0:page;
        limit = isNull(limit)?10:limit;
        var index = layer.load(3);
        $.ajax({
            url : "/CivilAffairs/manager/searchBeneficiaryByName",
            type : "post",
            data : {"searchName":searchName,"villageId":village,"page":page,"limit":limit},
            async : false,
            dataType : "json",
            success : function(result) {
                layer.close(index);
                if("0000"==result.status){
                    laytpl(beneficiaryTpl).render(result.data.data, function(html) {
                        $(".beneficiary_content").html(html);
                    });
                    //重新渲染
                    form.render('checkbox');
                    //需要重新加载分页
                    if(searchCount!=result.data.count || name != searchName){
                        searchCount = result.data.count;
                        name = searchName;
                        //分页组件
                        layPage.render({
                            elem: 'news-page'
                            ,count: result.data.count //数据总数，从服务端得到
                            ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                            ,jump: function(obj, first){
                                //首次不执行
                                if(!first){
                                    searchNameInfo(searchName,obj.curr,obj.limit);
                                }
                            }
                        });
                    }
                }else{
                    var villageName = getVillageNameById(village);
                    var detail = isNull(village)&&isNull(villageName)?"":"在乡镇[ "+villageName+" ]中";
                    layer.msg(detail+"未查询到姓名[ "+searchName+" ]的信息",{icon:2});
                }

            },
            error:function(result){
                layer.close(index);
                reqError(result,"搜索名字信息异常");
            }
        });
    }

    //根据乡镇id获取乡镇名
    function getVillageNameById(villageId){
        var villageName = "";
        $("#villages option").each(function () {
            if($(this).val()==villageId){
                villageName = $(this).text();
            }
        });
        return villageName;
    }

    //通过判断文章是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="open"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="open"]):checked')
        if(childChecked.length == child.length){
            $(data.elem).parents('table').find('thead input#selectAll').get(0).checked = true;
        }else{
            $(data.elem).parents('table').find('thead input#selectAll').get(0).checked = false;
        }
        form.render('checkbox');
    });

});